package com.msmall.community.diary.dao.hibernate;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.msmall.base.dao.hibernate.BaseDaoHibernate;
import com.msmall.community.diary.dao.DiaryDao;
import com.msmall.community.diary.model.Diary;
import com.msmall.community.diary.model.DiaryReply;

public class DiaryDaoHibernate extends BaseDaoHibernate implements DiaryDao{

	/**
	 * 通过id查找日记的前一张日记,按ID排序，如果是第一张，跳到最后一张
	 */
	public Diary getDiaryPreByid(Long diaryid) throws Exception{
		try{
			StringBuffer buffer = new StringBuffer();
			buffer.append("select a.* from base_diary a,")
			.append(" ( select b.user_id FROM base_diary b where b.diary_id=? ) c ")
			.append(" where a.user_id=c.user_id and a.diary_id<? ORDER BY a.diary_id DESC limit 1");
			Session session = super.getSession();
			SQLQuery query = session.createSQLQuery(buffer.toString()).addEntity(Diary.class);
			query.setParameter(0, diaryid);
			query.setParameter(1, diaryid);
			List list = query.list();
			if(list != null && list.size() >0){
				return (Diary) list.get(0);
			}
			super.releaseSession(session);
			return null;
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
	/**
	 * 通过id查找照片的后一日记,按ID排序，如果是最后一张，跳到第一张
	 */
	public Diary getDiaryNextByid(Long diaryid) throws Exception{
		try{
			StringBuffer buffer = new StringBuffer();
			buffer.append("select a.* from base_diary a,")
			.append(" ( select b.user_id FROM base_diary b where b.diary_id=? ) c ")
			.append(" where a.user_id=c.user_id and a.diary_id>? ORDER BY a.diary_id ASC limit 1");
			Session session = super.getSession();
			SQLQuery query = session.createSQLQuery(buffer.toString()).addEntity(Diary.class);
			query.setParameter(0, diaryid);
			query.setParameter(1, diaryid);
			List list = query.list();
			if(list != null && list.size() >0){
				return (Diary) list.get(0);
			}
			super.releaseSession(session);
			return null;
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
	/**
	 * 获得日记的所有评论
	 */
	public List<DiaryReply> getReplysByDiaryid(Long diaryid)throws Exception{
		try{
			String tempsql = "FROM DiaryReply where diaryid=?";
			return getHibernateTemplate().find(tempsql, new Object[]{diaryid});
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
}
